package com.jirong.shop.rabbitMQ;

import com.jirong.shop.pojo.SeckillMessage;
import com.jirong.shop.pojo.TUser;
import com.jirong.shop.service.TGoodsService;
import com.jirong.shop.service.TOrderService;
import com.jirong.shop.utils.JsonUtil;
import com.jirong.shop.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class MQReceiver {
    @Autowired
    private TGoodsService goodsService;
    @Autowired
    private TOrderService orderService;
    @Autowired
    @Qualifier("redisTemplate1")
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = "seckillQueue")
    public void receive(String msg) {
        log.info("QUEUE接受消息：" + msg);
//        将传过来的JSON数据转回对象
        SeckillMessage message = JsonUtil.jsonStr2Object(msg, SeckillMessage.class);
        Long goodId = message.getGoodId();
        TUser user = message.getUser();
//        下单再查一边库存
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodId);
        if (goods.getStockCount() < 1) {
            return;
        }
        String seckillOrderJson = (String) redisTemplate.opsForValue().get("order:"+user.getId()+":"+goodId);
        if (!StringUtils.isEmpty(seckillOrderJson)) {
            return;
        }
        orderService.secKill(user,goods);
    }

}
